<?php

namespace App\Http\Controllers\V1\Api;

use App\Helper\AliYunSmsNotice;
use App\Http\Requests\UserRequest;

use App\Models\V1\Admins;
use App\Models\V1\Advert;
use App\Models\V1\Bank;
use App\Models\V1\BankClass;
use App\Models\V1\DeveloperOperationLog;
use App\Models\V1\GameVersion;
use App\Models\V1\SysPermission;
use App\Models\V1\SysRole;
use App\Models\V1\Users;
use Earnp\GoogleAuthenticator\GoogleAuthenticator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Overtrue\Socialite\User;

class UserController extends BaseController
{

    protected AliYunSmsNotice $aliYunSmsNoticeRe;


    public function __construct()
    {
        parent::__construct(); // 调用父类的构造函数
        $this->aliYunSmsNoticeRe = AliYunSmsNotice::getInstance();
    }

    /**
     * 个人认证提交
     * @param Request $request
     * @return void
     */
    public function submitAc(Request $request)
    {
        $real_name = $request->input('real_name', '');
        $id_card = $request->input('id_card', '');
        $auth_video = $request->input('auth_video', '');
        $identity_front = $request->input('identity_front', '');
        $identity_back = $request->input('identity_back', '');

        $open_bank_class_id = $request->input('open_bank_class_id', '');//银行分类id
        $card_number = $request->input('card_number', '');
        if (empty($id_card) || empty($real_name) || empty($open_bank_class_id) || empty($card_number)) {
            return ajax_output(300, "参数错误");
        }
        try {
            DB::beginTransaction();
            $id = auth('box')->id();

            $bank_class = new BankClass();
            $bank_class_data = $bank_class->where('id', $open_bank_class_id)->first();//银行卡分类

            $vo = Users::find($id);
            $vo->update([
                'id_card' => $id_card,
                'real_name' => $real_name,
                'auth_video' => $auth_video,
                'identity_front' => $identity_front,
                'identity_back' => $identity_back,
                'audit_status' => 2,
                'class_id' => $open_bank_class_id,
                'open_bank' => $bank_class_data['name'],
                'open_bank_e' => $bank_class_data['e_name'],
                'card_number' => $card_number,
                'open_bank_log' => $bank_class_data['log'],
            ]);
            // 发送业务通知短信
            $this->aliYunSmsNoticeRe->SendCode('开发者提交个人认证');
            DB::commit();

        } catch (\Exception $e) {
            DB::rollBack();
            return ajax_output(300, "数据异常:" . $e->getMessage());
        }
        return ajax_output(200, "提交个人认证成功");
    }


    /**
     * 修改个人信息
     * @param Request $request
     * @return void
     */
//    public function updateUser(Request $request)
    public function updateUser(UserRequest $request)
    {
        $request->validate('setInfo');

        try {
            $id = auth('box')->id();
            $vo = Users::find($id);

            $data = [];
            if ($request->filled('avatar')) {
                $data['avatar'] = $request->input('avatar');
            }

            if ($request->filled('username')) {
                $data['username'] = $request->input('username');
            }

            if ($request->filled('username')) {
                $data['mobile'] = $request->input('mobile');
            }

            if ($request->filled('qq')) {
                $data['qq'] = $request->input('qq');
            }

            if ($request->filled('weixin')) {
                $data['weixin'] = $request->input('weixin');
            }

            if ($request->filled('password')) {
                $data['password'] = bcrypt($request->input('password'));
            }

            $vo->update($data);
            // 添加开发者操作日志
            DeveloperOperationLog::query()->create([
                'user' => $id,
                'ip' => $request->getClientIp(),
                'ulid' => time(),
                'attributes' => !empty($request->all()) ? json_encode($request->all()) : null,
                'remark' => '修改个人信息',
            ]);
            return ajax_output(200, "修改成功");
        } catch (\Exception $e) {

            return ajax_output(300, "修改失败");
        }


    }


    /**
     * 修改安全密码
     * @param Request $request
     * @return void
     */
    public function updateSafePassword(Request $request)
    {
        $safe_password = $request->input('safe_password', '');

        try {
            $id = auth('box')->id();
            $vo = Users::find($id);
            $vo->where('id', $id)->update([
                'safe_password' => bcrypt($safe_password),
            ]);
            return ajax_output(200, "修改成功");
        } catch (\Exception $e) {

            return ajax_output(300, "修改失败");
        }


    }


    /**
     * 用户详情
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserInfo(Request $request)
    {
        $id = auth('box')->id();
        $data = Users::find($id);

        if (!$data) {
            return ajax_output(300, "查询失败");
        } else {

            $data['s_num'] = Users::query()->where('pid', $data['id'])->count();
            $data['m_game_num'] = GameVersion::query()->where('product', 'bq01H7ESMBTPNK0TTTX49JNP336E')
                ->where('user', $data['id'])->where('state', 1)
                ->count();

            return ajax_output(200, "查询成功", $data);
        }
    }


    /**
     * 查询用户银行卡
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserBank(Request $request)
    {
        $id = auth('box')->id();
        $data = Bank::where('users_id', $id)->first();
        return ajax_output(200, "查询成功", $data);

    }


    /**
     * 查询银行卡分类列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBankClassList(Request $request)
    {

        $sort = $request->input('sort', 'id');
        $order = $request->input('order', 'asc');
        $pageSize = $request->input('pageSize', 10);
        $query = BankClass::query();
        $query->where('state', 1);
        $query->orderBy($sort, $order);
        $data = $query->paginate($pageSize);
        return ajax_output(200, "成功", $data);

    }

    /**
     * 用户列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {

        $query = Admins::query();

        $pageSize = $request->input('pageSize', 10);
        $order = $request->input('order', 'desc');
        $sort = $request->input('sort', 'id');

        if ($request->filled('username')) {
            $query->where('username', 'like', '%' . $request->input('username') . '%');
        }
        if ($request->filled('mobile')) {
            $query->where('mobile', "like", "%" . $request->input('mobile') . "%");
        }
        if ($request->filled('state')) {
            $query->where('state', $request->input('state'));
        }
        if ($request->filled('begin_at')) {
            $query->where('created_at', '>=', $request->input('begin_at'));
        }
        if ($request->filled('end_at')) {
            $query->where('created_at', '<=', $request->input('end_at'));
        }
        $query->orderBy($sort, $order);
        $data = $query->paginate($pageSize);
        $role_model = new SysRole();
        foreach ($data->items() as &$value) {
            $value->roles = $role_model->getRoles($value->id, $value->mch_id);
        }
        return ajax_output(200, "成功", $data);
    }

    /**
     * 选择商务
     * @param Request $request
     * @return void
     */
    public function selectList(Request $request)
    {
        $query = Admins::query();
        $data = [];
        if ($request->filled('keyword')) {
            $query->where("username", "like", "%" . $request->input('keyword') . "%")->orWhere('nickname', "like", "%" . $request->input('keyword') . "%");
            $data = $query->select('id as value', 'username as label')->get();
        }
        return ajax_output(200, "成功", $data);
    }

    /**
     * 新增用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        try {
            DB::beginTransaction();
            $role_ids = $request->input('role_ids', []);
            $admin_model = new Admins();
            $vo = $admin_model->create([
                'username' => $request->input('username', ""),
                'password' => bcrypt($request->input('password', "")),
                'mobile' => $request->input('mobile', ""),
                'nickname' => $request->input('nickname', ""),
                'email' => $request->input('email', ""),
                'qq' => $request->input('qq', ""),
                'mch_id' => $this->user->mch_id,
                'sex' => 1,
                'is_super' => 0,//非超级管理员
                'is_google_auth' => $request->input('is_google_auth', 0),
                'google_secret' => $request->input('google_secret', ""),
                'state' => (int)$request->input('state', 1),
                'remark' => $request->input('remark', "")
            ]);
            //设置当前用户的用户组
            $role_model = new SysRole();
            $role_model->setRoles($role_ids, $vo->id, $vo->mch_id);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return ajax_output(300, "数据异常:" . $e->getMessage());
        }
        return ajax_output(200, "成功");
    }


    /**
     * 更新用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, $id)
    {
        try {
            DB::beginTransaction();
            $role_ids = $request->input('role_ids', []);
            $admin_model = new Admins();
            $vo = $admin_model->find($id);
            if (!$vo) {
                return ajax_output(300, "数据不存在");
            }
            $vo->update([
                'mobile' => $request->input('mobile', ""),
                'nickname' => $request->input('nickname', ""),
                'email' => $request->input('email', ""),
                'qq' => $request->input('qq', ""),
                'state' => (int)$request->input('state', 0),
                'remark' => $request->input('remark', "")
            ]);

            ///设置当前用户的用户组
            $role_model = new SysRole();
            $role_model->setRoles($role_ids, $vo->id, $vo->mch_id);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return ajax_output(300, "数据异常:" . $e->getMessage());
        }
        return ajax_output(200, "成功");
    }

    /**
     * 用户详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function show(Request $request, $id)
    {
        $admin_model = new Admins();
        $vo = $admin_model->find($id);

        //查询用户的角色
        $role_model = new SysRole();
        $roles = $role_model->getRoles($vo->id, $vo->mch_id);
        $role_ids = [];
        foreach ($roles as $role) {
            $role_ids[] = $role->id;
        }
        $vo->role_ids = $role_ids;
        return ajax_output(200, "成功", $vo);
    }

    /**
     * 重置密码
     * @param Request $request
     * @return void
     */
    public function resetPwd(Request $request)
    {
        $password = $request->input('password');
        $userId = $request->input('userId', 0);
        $admin_model = new Admins();
        $vo = $admin_model->find($userId);
        $vo->password = bcrypt($password);
        $vo->save();
        return ajax_output(200, "成功");
    }

    /**
     * 修改状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeStatus(Request $request)
    {
        $userId = $request->input('userId', 0);
        $admin_model = new Admins();
        $vo = $admin_model->find($userId);
        if (!$vo) {
            return ajax_output(300, "数据不存在");
        }
        $vo->state = (int)$request->input('status', 1);
        $vo->save();
        return ajax_output(200, "成功");
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getInfo(Request $request)
    {
        //查询用户的角色
        $role_model = new SysRole();
        $roles = $role_model->getRoles($this->user->id, $this->user->mch_id);
        $role_keys = $permissions_array = $allow_permissions = [];
        $permission_model = new SysPermission();
        foreach ($roles as $role) {
            $role_keys[] = $role->title;
            list($node, $permissions) = $permission_model->getPermissions($role->id);
            $permissions_array = array_merge($permissions_array, $permissions);
        }

        foreach ($permissions_array as $row) {
            if (!empty($row[1])) {
                $allow_permissions[] = $row[1];
            }
        }
        //查询当前用户权限
        $data = [
            'user' => $this->user,
            'roles' => ['admin'],//$role_keys,
            'permissions' => ["*:*:*"]//$allow_permissions//$allow_permissions//
        ];
        return ajax_output(200, "成功", $data);
    }

    /**
     * 个人信息
     * @param Request $request
     * @return void
     */
    public function profile(Request $request)
    {
        $admin_model = new Admins();
        $vo = $admin_model->select('username', 'mobile', 'nickname', 'email', 'qq', 'avatar', 'sex', 'is_google_auth', 'google_secret')->find($this->user->id);

        // 获取google秘钥
        if (empty($vo->google_secret)) {
            $google = GoogleAuthenticator::CreateSecret();
            $vo->google_secret = $google['secret'];
        }
        return ajax_output(200, "成功", $vo);
    }

    /**
     * 保存个人信息
     * @param Request $request
     * @return void
     */
    public function save_profile(Request $request)
    {
        $admin_model = new Admins();
        $vo = $admin_model->find($this->user->id);
        $vo->update([
            'mobile' => $request->input('mobile', ""),
            'nickname' => $request->input('nickname', ""),
            'avatar' => $request->input('avatar', ""),
            'email' => $request->input('email', ""),
            'qq' => $request->input('qq', ""),
            'sex' => $request->input('sex', 0),
        ]);
    }

    /**
     * 修改密码
     * @param Request $request
     * @return void
     */
    public function updatePwd(Request $request)
    {
        $admin_model = new Admins();
        $vo = $admin_model->find($this->user->id);
        $isCheck = \Hash::check($request->input('oldPassword'), $vo->password);
        if (!$isCheck) {//验证旧密码是否正确
            return ajax_output(300, "您输入的旧密码不正确，请重新输入");
        }
        $vo->password = bcrypt($request->input('newPassword'));
        $vo->save();
        return ajax_output(200, "成功");
    }


    /**
     * 获取当前用户的路由情况
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getRouters(Request $request)
    {
        $permission_model = new SysPermission();
        $permission_menus = $permission_model->getPermissionMenu($this->user->id);
        return ajax_output(200, "成功", $permission_menus);
    }

    /**
     * 获取用户权限
     * @param Request $request
     * @return void
     */
    public function permissions(Request $request)
    {
        $user_id = $request->input('user_id', 0);
        $role_model = new SysRole();
        $roles = $role_model->getRoles($user_id);//获取用户组
        if (empty($roles)) return false;

        $node_array = [];
        $permission_model = new SysPermission();
        foreach ($roles as $role) {
            list($node, $permissions) = $permission_model->getPermissions($role->id);
            $node_array = array_merge($node_array, $node);
        }

        $data['checkedKeys'] = $node_array;
        $data['menus'] = $permission_model->getAllPermission();
        return ajax_output(200, "成功", $data);
    }


    /**
     * 删除用户
     * @param Request $request
     * @param $ids
     * @return void
     */
    public function destroy(Request $request, $id)
    {
        $ids = explode(",", $id);
        foreach ($ids as $user_id) {
            //删除用户权限
            $role_model = new SysRole();
            $role_model->delRoles($user_id);
        }
        //删除用户
        $admin_model = new Admins();
        $admin_model->destroy($ids);
        return ajax_output(200, "成功");
    }

    /**
     * 首页统计信息
     * @return void
     */
    public function statistics(Request $request)
    {
        $begin_at = date("Y-m-d 00:00:00");
        $end_at = date("Y-m-d 23:59:59");
        $data = [
            'today_register' => Player::whereBetween('created_at', [$begin_at, $end_at])->count("*"),
            'today_pay' => PlayerRecharge::whereBetween('created_at', [$begin_at, $end_at])->where('state', 1)->sum('money'),
            'merchant_num' => MerchantInfo::count("*"),
            'game_num' => MerchantGames::where("state", 1)->count("*"),
            'work_order_pending' => WorkQuestion::whereIn('state', [3, 4])->count("*"),
            'task_pending' => GameTask::where('state', 0)->count("*"),
            'server_num' => MerchantServers::count("*"),
            'game_area_num' => GameArea::count("*")
        ];
        return ajax_output(200, "成功", $data);
    }
}
